import json
from flask import request,jsonify
from .alarm_data import add
from configparser import ConfigParser
import pymysql.cursors
# 读取配置文件
conf = ConfigParser()
conf.read("setting.ini",encoding='utf-8')
# 数据库连接
def mysql():
    mydb = pymysql.connect(
        host=conf.get("mysql_settings","host"),
        port=int(conf.get("mysql_settings","port")),
        user=conf.get("mysql_settings","user"),
        password=conf.get("mysql_settings","password"),
        database='data_info',
        cursorclass=pymysql.cursors.DictCursor
    )
    return mydb
# 海康超脑
def hk_alarm_sdk():
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = json.loads(request.data)
        data = '"'+str(jsons)+'"'
        sql = "insert into all_data (data,type) values(%s,'%s')"%(data,'hk_alarm_sdk')
        insert = cursor.execute(sql)
        mydb.commit()
        cursor.close()  # 关闭游标
        lCommand = jsons.get("lCommand")
        pic = jsons.get("pic")
        byIvmsChannel = jsons.get("byIvmsChannel")
        struDevIP  = jsons.get("struDevIP")
        time = getDwAbsTime(jsons.get("dwAbsTime"))
        if lCommand == '0x1102':
            alarmTypeName = '脱岗离岗报警'
            alarmType = '001e7548-8735-4b31-b30b-c9361a62c973'
            # 报警内容
            content ='脱岗离岗'
            jsonParam = {"deviceClassify": "1","number": str(struDevIP),"dataType": "alarm","alarmTime": time,"alarmType": alarmType,"alarmTypeName": alarmTypeName,"content": content,"url": "http://192.168.0.99:90/python/hk_alarm/pic/"+pic}
            print(jsonParam)
            add(jsonParam)
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close() # 关闭数据库
    return jsonify(
        msg="success",
        code=0
    )
def getDwAbsTime (dwAbsTime):

    YEAR = str((((dwAbsTime)>>26) + 2000))
    MONTH = str((((dwAbsTime)>>22) & 15))
    if len(MONTH) == 1:
        MONTH = '0'+MONTH
    DAY = str((((dwAbsTime)>>17) & 31))
    if len(DAY) == 1:
        DAY = '0'+DAY
    HOUR = str((((dwAbsTime)>>12) & 31))
    if len(HOUR) == 1:
        HOUR = '0'+HOUR
    MINUTE = str((((dwAbsTime)>>6) & 63))
    if len(MINUTE) == 1:
        MINUTE = '0'+MINUTE
    SECOND = str((((dwAbsTime)>>0) & 63))
    if len(SECOND) == 1:
        SECOND = '0'+SECOND
    return YEAR+"-"+MONTH+"-"+DAY+" "+HOUR+":"+MINUTE+":"+SECOND
